package com.example.service.impl;

import com.example.domain.UserDetail;
import com.example.domain.vo.LoginUserVo;
import com.example.exeption.BusinessException;
import com.example.service.ILoginService;
import com.example.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author ljs
 * @date 2025/7/21
 */
@Service
@Slf4j
public class LoginService implements ILoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JWTUtils jwtUtils;

    @Override
    public String login(LoginUserVo loginUserVo) {
        try {


            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUserVo.getUsername(),loginUserVo.getPassword());
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            UserDetail principal = (UserDetail) authenticate.getPrincipal();

            if (principal != null) {
                return jwtUtils.createToken(principal);
            }
        } catch (BadCredentialsException e) {
            // 密码错误
            throw new BusinessException(401, "用户名或密码错误");
        } catch (UsernameNotFoundException e) {
            // 用户不存在
            throw new BusinessException(401, "用户不存在");
        } catch (DisabledException e) {
            // 用户被禁用
            throw new BusinessException(403, "用户已被禁用");
        } catch (LockedException e) {
            // 用户被锁定
            throw new BusinessException(403, "用户已被锁定");
        } catch (AccountExpiredException e) {
            // 账户过期
            throw new BusinessException(403, "账户已过期");
        } catch (CredentialsExpiredException e) {
            // 凭证过期
            throw new BusinessException(403, "密码已过期");
        } catch (Exception e) {
            // 其他未知错误
            log.error("登录异常", e);
            throw new BusinessException(500, "登录失败，请稍后重试");
        }
        return null;
    }
}
